package com.gg.registration.hospital.mqListener;

import com.gg.registration.hospital.service.ScheduleService;
import com.gg.registration.model.hosp.Schedule;
import com.gg.registration.rabbitmq.constant.MQConstant;
import com.gg.registration.rabbitmq.service.RabbitService;
import com.gg.registration.vo.msm.MsmVo;
import com.gg.registration.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Author：  chenjunjia
 * Date：    2022/4/26 0:25
 * WeChat：  China_JoJo_
 */
@Component
public class HospitalListener {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstant.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MQConstant.EXCHANGE_DIRECT_ORDER),
            key = {MQConstant.ROUTING_ORDER}
    ))
    /**
     * 为什么这里不存在序列化问题呢？……
     */
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) throws IOException {
        MsmVo msmVo = orderMqVo.getMsmVo();
        //用 OrderMqVo 里面的参数判断 是下单还是取消预约
        if (null != orderMqVo.getAvailableNumber()) {
            //下单成功更新预约数
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            //更新排班信息
            scheduleService.update(schedule);

        } else {
            //这里是取消预约操作
            //修改可预约数
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            int availableNumber = schedule.getAvailableNumber().intValue() + 1;
            schedule.setAvailableNumber(availableNumber);
            //更新排班信息
            scheduleService.update(schedule);
        }
        //然后发送短信
        if (null != msmVo) {
            /**
             * 这里改一改，msmVo传不过去那就就用Map
             */
            Map smsMap = new HashMap();
            smsMap.put("phone", msmVo.getPhone());
            smsMap.put("code", "999888");
            //发送短信
            rabbitService.sendMessage(MQConstant.EXCHANGE_DIRECT_MSM, MQConstant.ROUTING_MSM_ITEM, smsMap);
        }
    }
}
